<?php

namespace app\helper\ChannelSdk;

use app\atrait\Single;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Arr;

class XieXiao
{

    use Single;

    private string $appId;
    private string $payKey;


    public function __construct()
    {
        $this->appId = '0ca961c1a229401c';
        $this->payKey = 'fae20ce7d44b4e30b3dbdc170ac0614d';
    }


    public function loginAuth($uid): array
    {

        $url = 'https://sdk.588yyds.com';

        $param = [
            'app_id' => $this->appId,
            'uid' => $uid,
            'timestamp' => time()
        ];

        $param['sign'] = $this->Sign($param);

        $http = new Client();
        try {
            $res = $http->request('POST', $url . '/tools/gamefactor.ashx?action=factor_login', [
                'form_params' => $param,
            ]);
            $result = json_decode($res->getBody(), true);
        } catch (GuzzleException $e) {
            return [
                'state' => false,
                'message' => $e->getMessage(),
            ];
        }

        return [
            'state' => $result['status'] === 1,
            'message' => $result['status'] === 1 ? '' : $result['msg'],
            'data' => $result['status'] === 1 ? [
                'uid' => $uid,
            ] : [],
        ];

    }


    /**
     * 参数签名
     *
     * @param $param
     * @return string
     */
    public function Sign($param): string
    {

        $signStr = Arr::query(Arr::sortRecursive($param));
        $signStr .= '&pay_key=' . $this->payKey;

        return md5($signStr);

    }

}
